import wizard
import pooler
from tools.misc import UpdateableStr,UpdateableDict
import time
import operator
from osv import osv, fields
from osv.orm import intersect
import tools.sql
from tools import config
from tools.translate import _
from mx import DateTime
import netsvc

FORM = UpdateableStr()

Fields=UpdateableDict()
Forms=UpdateableStr()

def _check(self, cr, uid, data, context):
    pool = pooler.get_pool(cr.dbname)
    sale_obj = pool.get('sale.order')
    sale=sale_obj.browse(cr,uid,data['id'],context=context)
    
    contract_id = sale.contract_id
     
    line_check=True #Tam thoi
    finish=False
    if contract_id:
        finish=True
    if finish:
        return 'end'
    else:
        return 'create_new_contract'

   
def _input_main(self, cr, uid, data, context):
    pool = pooler.get_pool(cr.dbname)
    sale_obj = pool.get('sale.order')

    sale=sale_obj.browse(cr,uid,data['id'],context=context)
    #prj_name=sale_obj.read(cr,uid,data['id'],['project_name'])['project_name']
    prj_name = sale.project_name
    owner=sale.owner_id.id
    client_id=sale.partner_id.id
    contract_des = sale.description
    if sale.contract_id:
        contract_id = sale.contract_id.id 
    else:
        contract_id = False
        
    typeaction=''

    #New code Contract
    cr.execute("Select * from vwnewcode_contract order by newcode asc")
    list_newcode=''
    for ncode,nname in cr.fetchall(): 
        if list_newcode=='':
            list_newcode="('"+ncode+"','"+ncode+": "+nname+"')"
        else:
            list_newcode=list_newcode+",('"+ncode+"','"+ncode+": "+nname+"')"
    list_newcode="["+list_newcode+"]"
    
    #Existing code
    cr.execute("Select contract_no,description from kdvn_contract_client where to_char(date,'YY')=to_char(now(),'YY')")

    list_exist_contract=''
    list_exist_contract1 = ''
    for ncode,nname in cr.fetchall():
        nname=nname.replace("'","`")
        if list_exist_contract=='':
            list_exist_contract="('"+ncode+"','"+ncode+": "+nname+"')"
            list_exist_contract1 ='("'+ncode+'","'+ncode+': '+nname+'")'
        else:
            list_exist_contract1=list_exist_contract1+',("'+ncode+'","'+ncode+': '+nname+'")'
            list_exist_contract=list_exist_contract+",('"+ncode+"','"+ncode+": "+nname + "')"

    list_exist_contract="["+list_exist_contract+"]"
    list_exist_contract1 = "["+list_exist_contract1+"]"
    
    Fields['client_id']={'string':'Client','type':'many2one','relation':"res.partner",'readonly':True,'default': lambda *a:client_id}
    Fields['owner_id']={'string':'Owner','type':'many2one','relation':"res.partner",'readonly':True,'default': lambda *a:owner}
    
    Fields['contract_code_suggest']={'string':'New Code','type':'selection','selection':eval(list_newcode)}
    Fields['contract_code_new']={'string':'Job Code','type':'char','size':128}
    Fields['contract_name_new']={'string':'Job Name','type':'char','size':256,'default':lambda *a:contract_des}#,'default': lambda *a:prj_name}
    try:
        Fields['contract_code_exist']={'string':'New Code','type':'selection','selection':eval(list_exist_contract)}
    except:
        Fields['contract_code_exist']={'string':'New Code','type':'selection','selection':eval(list_exist_contract1)}

    Forms.string='''<?xml version="1.0"?>
                    <form string="Create New Contract">
                            <separator string="Customer Infomation" colspan="4"/>
                            <field name="owner_id"/>
                            <field name="client_id"/>
                            <separator string="Contract Info." colspan="4"/>
                            <field name="contract_code_exist" string="Exist Contract Code This Year" on_change="_onchange_contract_exist()"/>
                            <field name="contract_code_suggest" on_change="_onchange(contract_code_suggest)" string="Suggest Contract New Code"/>
                            <field name="contract_code_new" string="Contract New Code" attrs="{'required':[('contract_name_new','!=',False)]}"/>
                            <field name="contract_name_new" string="Contract Name" attrs="{'required':[('contract_code_new','!=',False)]}"/>
                    </form>'''
    return {}


def _update_(self, cr, uid, data, context):
    
    pool = pooler.get_pool(cr.dbname)
    sale_obj = pool.get('sale.order')
    kdvn_ctc_obj = pool.get('kdvn.contract.client')    


#Thieu contract
    #Mechanical & Electrical
    if data['form']:
        contract_id = False
        
        quotation_check_list_a = False
        
        if data['form']['contract_code_new']:
            cr.execute("Select \
                               owner_id,partner_id,\
                               partner_order_id,partner_invoice_id,\
                               taxes_percent,with_holding_taxes_percent,\
                               project_name\
                        from sale_order where id=%s" % data['id']) #Remove currency ID
            
            
            quotation_check_list_a = cr.dictfetchone()
                       
            prj_owner_id = False
            prj_partner_id = False
            prj_partner_order_id = False
            prj_partner_invoice_id = False
            curr_id = False
            project_name = False
            
            vat_per = 0.0
            wh_per = 0.0

            if quotation_check_list_a:

                #curr_id = quotation_check_list_a['currency_id']

                prj_owner_id = quotation_check_list_a['owner_id']
                prj_client_id = quotation_check_list_a['partner_id']
                prj_partner_order_id = quotation_check_list_a['partner_order_id']
                prj_partner_invoice_id = quotation_check_list_a['partner_invoice_id']
                vat_per = quotation_check_list_a['taxes_percent']
                wh_per = quotation_check_list_a['with_holding_taxes_percent']
            
            contract_code=data['form']['contract_code_new']
            contract_name=data['form']['contract_name_new']
            cr.execute("Select distinct currency_id from quotation_submit_line where order_id = %s" % data['id'])
            contract_lines = []
            for curr_id in cr.fetchall():
                contract_lines.append((0,False,{'currency_id':curr_id}))
            new_e_vals={
                        "currency_line":contract_lines,
                        "contract_no":contract_code,"description":contract_name,
                        'owner_id':prj_owner_id,'client_id':prj_client_id,
                        'address_id':prj_partner_order_id,
                        'invoice_address_id':prj_partner_invoice_id,
                        'project_name':project_name,"with_holding_taxes_percent":wh_per,"taxes_percent":vat_per
                        }
#            cr.execute("Select distinct \
#                               currency_id\
#                        from sale_order_line where coalesce(currency_id,0)>0 and order_id=%s" % data['id'])
#            curr_ids = []
#            for curr in cr.fetchall():
#                curr_ids.append(curr[0]) 
#            ctx={'currency_ids':curr_ids}
            
            contract_id=kdvn_ctc_obj.create(cr,uid,new_e_vals,{})
            
        elif data['form']['contract_code_exist']:
            contract_exist_code=data['form']['contract_code_exist']
            contract_id=kdvn_ctc_obj.search(cr,uid,[('contract_no','=',contract_exist_code)])[0]
            
        if contract_id:
            sale_obj.write(cr,uid,data['id'],{'contract_id':contract_id})
    return {}

class quotation_to_contract(osv.osv_memory): #Using onchange only
    _name='wizard.quotation_to_contract'
    _auto=False

    def _onchange_contract_exist(self, cr, uid, ids,pinput=False):
        return {'value':{'contract_code_new':False,'contract_name_new':False,'contract_code_suggest':False}}
    
    def _onchange(self, cr, uid, ids, pinput=False):
        return {'value':{'contract_code_new':pinput,'contract_code_exist':False}}

quotation_to_contract()

class QuotationContract(wizard.interface):
    """
    Quotation and Contract
    """    
    
    def _open_contract(self, cr, uid, data, context): #This one temporary not in use
        pool_obj = pooler.get_pool(cr.dbname)
        sale_obj = pool_obj.get('sale.order')
        sale=sale_obj.browse(cr,uid,data['id'],context=context)
        job=sale.project_id.id
        #raise osv.except_osv("Error","%s" % data)
        return {
            'domain': "[('id','=',"+str(job)+")]",
            'name': 'Projects',
            'view_type': 'form',
            'view_mode': 'form,tree',
            'res_model': 'account.analytic.account',
            'res_id':job,
            'view_id':False,
            'target':'new',
            #'views': [(False,'tree'),(False,'form'),],
            'type': 'ir.actions.act_window',
        }

    states = {
        'init': {
            'actions': [],
            'result': {'type': 'choice','next_state':_check}},
                               
        'create_new_contract': {
            'actions': [_input_main],
            'result': {'type': 'form','arch': Forms,'fields':Fields,'state': [
                    ('finish', '_Ok', 'gtk-ok', True),
                    ('end', '_Cancel','gtk-cancel'),
                    ]
                      }},
        'finish': {
            'actions': [_update_],
            'result': {
                'type': 'state',
#                'action':_open_project,
                'state': 'end'
            }},
        'end': {
            'actions': [],
            'result': {
                'type': 'state',
#                'action':_open_project,
                'state': 'end'
            }},
    }
QuotationContract('quotation_to_contract')
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
